package com.douyin.util;

import java.util.HashMap;
import java.util.Map;

public class IPLocationUtil {
    
    /**
     * 根据IP地址获取地理位置信息
     * 这是一个简化的实现，实际项目中应该集成第三方IP地理位置服务
     * 如：高德、百度、ipapi.co等
     */
    public static Map<String, String> getLocationFromIP(String ip) {
        Map<String, String> location = new HashMap<>();
        
        if (ip == null || ip.trim().isEmpty()) {
            location.put("country", "unknown");
            location.put("region", "unknown");
            location.put("city", "unknown");
            return location;
        }
        
        // 处理本地IP
        if (isLocalIP(ip)) {
            location.put("country", "China");
            location.put("region", "Local");
            location.put("city", "Local");
            return location;
        }
        
        // 这里应该调用第三方IP地理位置API
        // 为了演示，我们根据IP段进行简单判断
        try {
            String[] parts = ip.split("\\.");
            if (parts.length == 4) {
                int firstOctet = Integer.parseInt(parts[0]);
                
                // 简单的IP段地理位置映射（实际应用中应该用专业的IP地理位置数据库）
                if (firstOctet >= 1 && firstOctet <= 126) {
                    // A类地址的简单映射
                    location.put("country", "China");
                    location.put("region", "Beijing");
                    location.put("city", "Beijing");
                } else if (firstOctet >= 128 && firstOctet <= 191) {
                    // B类地址的简单映射
                    location.put("country", "China");
                    location.put("region", "Shanghai");
                    location.put("city", "Shanghai");
                } else {
                    // C类地址的简单映射
                    location.put("country", "China");
                    location.put("region", "Guangdong");
                    location.put("city", "Shenzhen");
                }
            } else {
                location.put("country", "unknown");
                location.put("region", "unknown");
                location.put("city", "unknown");
            }
        } catch (Exception e) {
            location.put("country", "unknown");
            location.put("region", "unknown");
            location.put("city", "unknown");
        }
        
        return location;
    }
    
    /**
     * 判断是否为本地IP
     */
    private static boolean isLocalIP(String ip) {
        return ip.equals("127.0.0.1") || 
               ip.equals("0:0:0:0:0:0:0:1") || 
               ip.equals("::1") ||
               ip.startsWith("192.168.") ||
               ip.startsWith("10.") ||
               (ip.startsWith("172.") && isInRange(ip, 16, 31));
    }
    
    /**
     * 判断172.x.x.x是否在指定范围内
     */
    private static boolean isInRange(String ip, int min, int max) {
        try {
            String[] parts = ip.split("\\.");
            int second = Integer.parseInt(parts[1]);
            return second >= min && second <= max;
        } catch (Exception e) {
            return false;
        }
    }
}